<?php
declare (strict_types=1);

namespace app\organization\controller\learn;

use app\common\controller\Frontend;
use app\common\model\banxi\learn\LearnSkRecord as LearnSkRecordModel;
use app\common\model\banxi\learn\LearnSubjectQuestionRecord;
use app\common\model\banxi\organization\Organization as OrganizationModel;
use app\common\service\ExportService;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\facade\Validate;
use think\validate\ValidateRule;

class LearnSkRecord extends Frontend
{
    protected array $noNeedLogin = [];
    protected array $noNeedPermission = [];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new LearnSkRecordModel();
    }


    /**
     * 分页查询
     * @return void
     * @throws DbException
     */
    public function listPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query"]);
        $organizationId = $this->auth->organizationId;
        $organizationModel = new OrganizationModel();
        $organizationIds = $organizationModel->getSonOrganization($organizationId);
        $param['query']['IN_studentOrgId'] = $organizationIds;
        $param['query']['EQ_isEnd'] = 1;
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $list = $this->model->with([
            'studentInfo' => function ($query) {
                $query->field('id,name');
            }, 'trainerInfo' => function ($query) {
                $query->field('id,name');
            }, 'organizationBaseInfo' => function ($query) {
                $query->field('id,name,managerName');
            }])
            ->where($where)
            ->order(['id' => 'asc'])
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit'],
            ])->each(function ($item) {
                if ($item['studentOrgId'] == 0) {
                    $organizationModel = new OrganizationModel();
                    $item['organizationBaseInfo'] = $organizationModel->getOrganizationInfo();
                }
            });
        $this->ok('操作成功', result_row($list));
    }

    /**
     * 查询
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    // public function get1()
    // {
    //     $param = $this->request->param(["query" => []]);
    //     if (empty($param['query'])) {
    //         $this->fail('请传递你要查询的记录');
    //     }
    //     $where = get_query($param);
    //     $info = $this->model->with([
    //         'studentInfo' => function ($query) {
    //             $query->field('id,name');
    //         }, 'trainerInfo' => function ($query) {
    //             $query->field('id,name');
    //         }, 'organizationBaseInfo' => function ($query) {
    //             $query->field('id,name,managerName');
    //         }, 'accountClassHour'])->where($where)->find();
    //     if (empty($info)) {
    //         $this->fail('记录不存在');
    //     }
    //     if (!$info['organizationBaseInfo']) {
    //         $organizationModel = new OrganizationModel();
    //         $info['organizationBaseInfo'] = $organizationModel->getOrganizationInfo();
    //     }
    //     $this->ok('操作成功', $info);
    // }

    public function get()
    {
        $param = $this->request->param(["query" => []]);
        if (empty($param['query'])) {
            $this->fail('请传递你要查询的记录');
        }
        $where = get_query($param);
        $learningReport = $this->model->with([
            'studentInfo' => function ($query) {
                $query->field('id,name');
            }, 'trainerInfo' => function ($query) {
                $query->field('id,name');
            }, 'organizationBaseInfo' => function ($query) {
                $query->field('id,name,managerName');
            }, 'accountClassHour'
        ])->where($where)->find();
        if (empty($learningReport)) {
            $this->fail('记录不存在');
        }
        //初始化全科练习数据
        $learningReport['inSubjectQuestion'] = [
            'questionNum' => 0,
            'rightRate' => 0
        ];
        $learningReport['afterSubjectQuestion'] = [
            'questionNum' => 0,
            'rightRate' => 0
        ];
        $LearnSubjectQuestionRecordModel = new LearnSubjectQuestionRecord();
        //全科随堂练习数据
        $in_subject_question_record = $LearnSubjectQuestionRecordModel->where(['skRecordId'=>$learningReport['id'],'exerciseType'=>2])->find();
        if ($in_subject_question_record){
            $learningReport['inSubjectQuestion'] = [
                'questionNum' => $in_subject_question_record['totalNum'],
                'rightRate' => $in_subject_question_record['rightRate']
            ];
        }
        //全科课后作业数据
        $after_subject_question_record = $LearnSubjectQuestionRecordModel->where(['skRecordId'=>$learningReport['id'],'exerciseType'=>3])->find();
        if ($after_subject_question_record){
            $learningReport['afterSubjectQuestion'] = [
                'questionNum' => $after_subject_question_record['totalNum'],
                'rightRate' => $after_subject_question_record['rightRate']
            ];
        }

        $this->ok('操作成功', removeNull($learningReport));
    }

    public function exportExcel()
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query"]);
        $organizationId = $this->auth->organizationId;
        $organizationModel = new OrganizationModel();
        $organizationIds = $organizationModel->getSonOrganization($organizationId);
        $param['query']['IN_studentOrgId'] = $organizationIds;
        $param['query']['EQ_isEnd'] = 1;
        //查询条件解析
        $where = get_query($param);
        $list = $this->model->with([
            'studentInfo' => function ($query) {
                $query->field('id,name');
            },
            'trainerInfo' => function ($query) {
                $query->field('id,name');
            },
            'organizationBaseInfo' => function ($query) {
                $query->field('id,name,managerName');
            }])
            ->where($where)
            ->order(['id' => 'asc'])
            ->field('studentId,studentOrgId,trainerId,courseName,courseFullType,courseDeliveryType,learnTotalNum,learnCorrectNum,learnErrorNum,actualStartTime,actualEndTime,learnValidStatus')
            ->select();
        if (!count($list)) {
            $this->fail('导出失败，没有数据');
        }
        $exportService = new ExportService();
        $exportService->LearnSkRecordExport($list);

    }
}
